var config = require('../config')
var proxy = require('http-proxy-middleware')

function getProxy (opt) {
  opt = opt || {}
  var key = opt.key || 'ajax/proxy'
  var pathRewrite = {}
  opt.ajaxHost = opt.ajaxHost || config.ajaxHost
  pathRewrite['^/' + key] = ''
  var options = {
    target: 'http://' + opt.ajaxHost,
    changeOrigin: true,
    onProxyReq: (proxyReq, req, res) => {
      console.log('proxy----', 'http://' + opt.ajaxHost + req.path)
      console.log('token----', req.session.token)
      proxyReq.setHeader('token', req.session.token || '')
      if (opt.json) {
        proxyReq.setHeader('Content-Type', 'application/json')
      }
    },
    pathRewrite: pathRewrite
  }
  var apiProxy = proxy(options)
  return apiProxy
}

module.exports = getProxy
